import axios, { type AxiosRequestConfig } from 'axios';

interface ResponseData<T = any> {
  data: T;
  errCode: number;
  errMsg: string;
}

export const request = async <T = any>(
  _url: string,
  config: AxiosRequestConfig = {}
): Promise<ResponseData<T> & { [k: string]: any }> => {
  const url = `${getBaseURL()}${_url}`;
  const res = await axios(url, {
    ...config,
    ...(config.method === 'get' || !config.method ? { params: config.data } : {}),
    headers: {
      'access-key': '134691',
      ...config.headers,
    },
  });

  if (res.data.errCode === 0) {
    return res.data;
  } else if (res.data.errCode === 400) {
    throw new Error(JSON.stringify(res.data));
  } else {
    throw new Error(JSON.stringify(res.data));
  }
};

export const getBaseURL = () => {
  return '/api/bizhi';
  // return 'https://tea.qingnian8.com/api/bizhi';
};
